package com.leyou.auth.job;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 当前对象就是用来获取并存放token的
 */
@Slf4j
@Component
public class TokenHolder {

    /**
     * token刷新间隔  24小时自动定时获取一次
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;
    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;

    private String token;

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProp;

    /**
     * 编写定时任务去获取token，给当前对象中的token属性赋值
     */
    @Scheduled(fixedRate = TOKEN_REFRESH_INTERVAL)
    public void autoGetToken(){
        //不断的去发起获取token的请求，只要获取到，就停止。
        while (true){
            try {
                //获取token
                String token = authService.appLogin(jwtProp.getApp().getId(), jwtProp.getApp().getSecret());
                //把token赋值给当前对象的私有属性
                this.token = token;
                //自己控制台看日志
                log.info("【{}服务获取token】成功！", jwtProp.getApp().getSecret());
                //获取到就停止获取
                break;
            }catch (Exception e){
                log.error("【{}服务获取token】失败！十秒钟后将会重试获取！", jwtProp.getApp().getSecret());
            }
            //如果没有获取到token，休息十秒钟再继续获取
            try {
                Thread.sleep(TOKEN_RETRY_INTERVAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 提供获取token的get方法
     */
    public String getToken() {
        return token;
    }

}
